package com.wyzz.hr.util.comparator;

import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.Comparator;

public class ObjectComparator extends IComparator implements Comparator {

	public ObjectComparator() {
		order = 1;
	}

	public ObjectComparator(int order, int compareMethod[]) {
		this.order = 1;
		setOrder(order);
		if (compareMethod.length > 0)
			setCompareMethod(compareMethod[0]);
	}

	public int compare(Object obj1, Object obj2) {
		if (obj1 == null && obj2 == null)
			return 0;
		if (obj1 == null)
			return -order;
		if (obj2 == null)
			return order;
		if (className == null
				|| className.compareTo(obj1.getClass().getName()) != 0) {
			className = obj1.getClass().getName();
			try {
				method = getMethodCompareTo(obj1, new int[] { compareMethod });
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (className == "java.lang.String")
			return comparePinYin((String) obj1, (String) obj2) * order;
		try {
			Integer resultTmp = (Integer) method.invoke(obj1,
					new Object[] { obj2 });
			if (resultTmp.intValue() != 0)
				return resultTmp.intValue() * order;
		} catch (Exception e) {
			System.out.print((new StringBuilder()).append(
					"==========error in compare: obj1,2=").append(
					obj1.getClass().getName()).append(", ").append(
					obj2.getClass().getName()).toString());
			e.printStackTrace();
		}
		return 0;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		className = null;
		method = null;
		if (order != 0)
			this.order = order;
	}

	private int order;
	private String className;
	private Method method;
}
